package com.tj.jinzao.presenter;

import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.business.session.emoji.MoonUtil;
import com.netease.nim.uikit.video.jzvd.JzvdStd;
import com.tj.jinzao.R;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BasePresenter;
import com.tj.jinzao.callback.IArticleView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.Comment;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.video.MyJzvdStd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 日记，文章列表处理
 * Created by wjy 2018/12/10.
 */
public class CommentPresenter extends BasePresenter<IArticleView<Article>> {

    public CommentPresenter(IArticleView<Article> view) {
        super(view);
    }

    public void getArticleById(long id) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.getArticleById(id, uId), new SubscriberCallBack<Article>(mView.getContext()) {
            @Override
            protected void onSuccess(Article article) {
                if (mView != null) mView.onRequestSuccess(article);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }
        });
    }

    public void setShowContentView(LayoutInflater inflater, String content, List<String> paths, boolean isVideo,String videoUrl, LinearLayout linearLayout, View.OnClickListener listener) {
        linearLayout.removeAllViews();
        if (TextUtils.isEmpty(content)) return;
        content = content.replace(Constant.ARTICLE_P1,"")
                .replace(Constant.ARTICLE_P2,"");
        String newContent = new String(content);
        //适配ios少一个articletag
        if (paths != null) {
            int key_times = getKeyTime(newContent, Constant.ARTICLE_TAG);
            if (key_times == paths.size() - 1) {
                newContent = new String(Constant.ARTICLE_TAG + content);
            }
        }
        //循环根据内容添加view
        int imageIndex = 0;
        do {
            View view = null;
            if (newContent.startsWith(Constant.ARTICLE_TAG)) {
                view = inflater.inflate(R.layout.item_public_image, null);
               MyJzvdStd myJzvdStd = view.findViewById(R.id.videoplayer);

//                JCVideoPlayerStandard jcVideoPlayerStandard = (JCVideoPlayerStandard) view.findViewById(R.id.videoplayer);
                ImageView imageView = view.findViewById(R.id.iv_image);
                view.findViewById(R.id.videoplayer).setVisibility(View.VISIBLE);
                imageView.setOnClickListener(listener);
                imageView.setTag(R.id.position, imageIndex);
                String path = paths.get(imageIndex);
                if (isVideo){
                    view.findViewById(R.id.iv_play).setVisibility(View.GONE);
                    myJzvdStd.setVisibility(View.VISIBLE);
//                    jcVideoPlayerStandard.setUp(Constant.IMAGE_PREFIX+videoUrl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
                    myJzvdStd.setUp(Constant.IMAGE_PREFIX + videoUrl
                            , "", JzvdStd.SCREEN_NORMAL);
                    if(path!=null&&path.contains(",")){
                        String images[] = path.split(",");
                        Glide.with(view.getContext()).load(Constant.IMAGE_PREFIX + images[0]).into(myJzvdStd.thumbImageView);
                    }else {
                        Glide.with(view.getContext()).load(Constant.IMAGE_PREFIX + path).into(myJzvdStd.thumbImageView);
                    }

                }else {
                    myJzvdStd.setVisibility(View.GONE);
                    if(path==null||path.equals("")){
                        imageView.setVisibility(View.GONE);
                    }else {
                        imageView.setVisibility(View.VISIBLE);
                    }
                    Glide.with(mView.getContext()).load(Constant.IMAGE_PREFIX + path).into(imageView);
                }
                view.findViewById(R.id.iv_delete).setVisibility(View.GONE);
                newContent = newContent.substring(Constant.ARTICLE_TAG.length(), newContent.length());
                imageIndex++;
            } else {
                int cutIndex = newContent.indexOf(Constant.ARTICLE_TAG);
                view = inflater.inflate(R.layout.item_public_textview, null);
                TextView textView = view.findViewById(R.id.tv_content);
                if (cutIndex != -1) {
                    String cutContent = newContent.substring(0, cutIndex);
                    MoonUtil.identifyFaceExpression(NimUIKit.getContext(), textView
                            , cutContent
                                    .replace(Constant.ARTICLE_P1,"")
                                    .replace(Constant.ARTICLE_P2,"")
                                    .replace(Constant.ARTICLE_TAG, "")
                            , ImageSpan.ALIGN_BOTTOM);

//                    MoonUtil.identifyFaceExpression(NimUIKit.getContext(), textView, cutContent, ImageSpan.ALIGN_BOTTOM);
                    newContent = newContent.substring(cutIndex, newContent.length());
                } else {
                    String cutContent = new String(newContent);
                    MoonUtil.identifyFaceExpression(NimUIKit.getContext(), textView
                            , cutContent
                                    .replace(Constant.ARTICLE_P1,"")
                                    .replace(Constant.ARTICLE_P2,"")
                                    .replace(Constant.ARTICLE_TAG, "")
                            , ImageSpan.ALIGN_BOTTOM);

//                    MoonUtil.identifyFaceExpression(NimUIKit.getContext(), textView, cutContent, ImageSpan.ALIGN_BOTTOM);
                    newContent = "";
                }
            }
            if (view != null) linearLayout.addView(view);
        } while (newContent.length() > 0);
    }

    public static int getKeyTime(String str, String key) {
        int index = 0; //定义变量。记录每一次找到的key的位置。
        int count = 0; //定义变量，记录出现的次数。

        //定义循环。只要索引到的位置不是-1，继续查找。
        while ((index = str.indexOf(key, index)) != -1) {
            //每循环一次，就要明确下一次查找的起始位置。
            index = index + key.length();
            //每查找一次，count自增。
            count++;
        }
        return count;
    }

    public void comment(long articleId, String content) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.replyArticle(uId, articleId, content), new SubscriberCallBack<Article>(mView.getContext()) {
            @Override
            protected void onSuccess(Article article) {
                if (mView != null) mView.onCommentSuccess(article);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public void reply(long articleId, int commentId, String content) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.replyComment(uId, articleId, commentId, content), new SubscriberCallBack<Article>(mView.getContext()) {
            @Override
            protected void onSuccess(Article article) {
                if (mView != null) mView.onCommentSuccess(article);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }


    public List<Comment> getCommentList(Article article) {
        HashMap<Integer, List<Comment>> map = new HashMap();
        List<Comment> newList = new ArrayList();
        List<Comment> origin = article.getComments();
        if (origin == null || origin.size() == 0) return origin;
        for (Comment comment : origin) {
            if (comment.getCommentId() != 0) {
                List<Comment> temp = null;
                if (map.containsKey(comment.getCommentId())) {
                    temp = map.get(comment.getCommentId());
                } else {
                    temp = new ArrayList();
                }
                temp.add(comment);
                map.put(comment.getCommentId(), temp);
            } else {
                newList.add(comment);
            }
        }
        List<Comment> finalList = new ArrayList();
        for (Comment comment : newList) {
            finalList.add(comment);
            if (map.containsKey(comment.getId())) {
                List<Comment> temp = map.get(comment.getId());
                for (Comment comment1 : temp) {
                    finalList.add(comment1);
                }
            }
        }
        return finalList;
    }

    public void praise(long articleId) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.praise(uId, articleId, 1), new SubscriberCallBack<String>(mView.getContext()) {
            @Override
            protected void onSuccess(String success) {
                if (mView != null) mView.onPraiseSuccess();
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public void collect(long articleId) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.praise(uId, articleId, 2), new SubscriberCallBack<String>(mView.getContext()) {
            @Override
            protected void onSuccess(String success) {
                if (mView != null) mView.onCollectSuccess();
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public void followArticle(long articleId) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.praise(uId, articleId, 3), new SubscriberCallBack<String>(mView.getContext()) {
            @Override
            protected void onSuccess(String success) {
                if (mView != null) mView.onFollowSuccess();
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public void next(long articleId, int type) {
        addSubscription(mApiService.getNextArticle(articleId, type), new SubscriberCallBack<Article>(mView.getContext()) {
            @Override
            protected void onSuccess(Article article) {
                if (mView != null) mView.onRequestSuccess(article);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }
}